import { ApiResponse, Article, History, Suggestion } from "@/types/data";
import { RootAction, RootThunkAction, SearchAction } from "@/types/store";
import request from "@/utils/request";
import { setLocalHistories } from "@/utils/storage";

export function getSuggestion(keyword: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{options: Suggestion}>>('/suggestion', {
      params: {
        q: keyword
      }
    })
    dispatch({
      type: 'search/suggestion',
      payload: res.data.data.options
    })
  }
}

export function addSearchList(newList: History): SearchAction {
  setLocalHistories([...newList])
  return {
    type: 'search/set_history',
    payload: [...newList]
  }
}

export function getResults(keyword:string, page: number): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{
      total_count: number
      results: Article[]
    }>>('search', {
      params:{
        q: keyword,
        page
      }
    })
    const {total_count, results} = res.data.data
    dispatch({
      type: 'search/saveResults',
      payload: {
        total_count,
        results
      }
    })
  }
}

export function clearResults(): RootAction {
  return {
    type: 'search/clearResults'
  }
}